package com.jcode222.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@ConditionalOnMissingClass("com.atomikos.jdbc.AtomikosDataSourceBean")
public class DataSourceConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSourceProperties db1Properties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSourceProperties db2Properties() {
        return new DataSourceProperties();
    }

    /**
     * 创建多个数据源 db1 和 db2
     * 此处的Primary，是设置一个Bean的优先级
     * 多数据源配置：https://docs.spring.io/spring-boot/docs/2.5.14/reference/html/howto.html#howto.data-access.configure-two-datasources
     * @return
     */
    @Primary
    @Bean(name = "db1")
    public DataSource getDateSource1(@Qualifier("db1Properties") DataSourceProperties db1Properties) {
        return db1Properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }
    @Bean(name = "db2")
    public DataSource getDateSource2(@Qualifier("db2Properties") DataSourceProperties db2Properties) {
        return db2Properties.initializeDataSourceBuilder().type(HikariDataSource .class).build();
    }

//    @Primary
//    @Bean(name = "db1")
//    @ConfigurationProperties(prefix = "spring.datasource.db1")
//    public DataSource getDateSource1() {
//        return DataSourceBuilder.create().build();
//    }
//    @Bean(name = "db2")
//    @ConfigurationProperties(prefix = "spring.datasource.db2")
//    public DataSource getDateSource2() {
//        return DataSourceBuilder.create().build();
//    }


    /**
     * 将多个数据源注入到DynamicDataSource
     * @param dataSource1
     * @param dataSource2
     * @return
     */
    @Bean(name = "dynamicDataSource")
    public DynamicDataSource DataSource(@Qualifier("db1") DataSource dataSource1,
                                        @Qualifier("db2") DataSource dataSource2) {
        Map<Object, Object> targetDataSource = new HashMap<>();
        targetDataSource.put(DataSourceType.DataBaseType.db1, dataSource1);
        targetDataSource.put(DataSourceType.DataBaseType.db2, dataSource2);
        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSource);
        dataSource.setDefaultTargetDataSource(dataSource1);
        return dataSource;
    }


    /**
     * 将动态数据源注入到SqlSessionFactory
     * @param dynamicDataSource
     * @return
     * @throws Exception
     */

//    @Bean(name = "SqlSessionFactory")
//    public SqlSessionFactory getSqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
//            throws Exception {
//        return createSqlSessionFactory(dynamicDataSource);
//    }

    private static SqlSessionFactory createSqlSessionFactory(DataSource dynamicDataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
        bean.setTypeAliasesPackage("com.jcode222.entity");
        return bean.getObject();
    }

    @Primary
    @Bean(name = "sqlSessionFactory1" )
    public SqlSessionFactory sqlSessionFactory1(@Qualifier("db1") DataSource dataSource) throws Exception {
        return createSqlSessionFactory(dataSource);
    }

    @Bean(name = "sqlSessionFactory2")
    public SqlSessionFactory sqlSessionFactory2(@Qualifier("db2") DataSource dataSource) throws Exception {
        return createSqlSessionFactory(dataSource);
    }

    @Bean(name = {"sqlSessionTemplate"})
    public CustomSqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory1,
                                                       @Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory2){
        Map<String,SqlSessionFactory> sqlSessionFactoryMap = new HashMap<>();
        sqlSessionFactoryMap.put("db1",sqlSessionFactory1);
        sqlSessionFactoryMap.put("db2",sqlSessionFactory2);
        CustomSqlSessionTemplate customSqlSessionTemplate = new CustomSqlSessionTemplate(sqlSessionFactory1);
        customSqlSessionTemplate.setTargetSqlSessionFactors(sqlSessionFactoryMap);
        return customSqlSessionTemplate;
    }

}